import React, { ReactDom, useState, useEffect, useRef } from "react";
import { Graph, Node, Edge, Shape, ToolsView } from "@antv/x6";
import { register } from "@antv/x6-react-shape";
import { Dropdown } from 'antd'


import "./zzzzz.css";
//   注册连线桩点
Graph.registerPortLayout(
  "metaNodeWrapparBox",
  (portsPositionArgs, elemBBox) => {
    return portsPositionArgs.map((_, index) => {
      console.log(_, index);
      return {
        position: {
          x: -10,
          y: 44 + 24 * index + 12,
        },
        angle: 0,
      };
    });
  }
);
class ContextMenuTool extends ToolsView.ToolItem {
  timer

  toggleContextMenu(visible, pos) {
    console.log(this.container)
    console.log(this)
    ReactDom.unmountComponentAtNode(this.container)
    document.removeEventListener('mousedown', this.onMouseDown)

    if (visible && pos) {
      ReactDom.render(
        <Dropdown
          open={true}
          trigger={['contextMenu']}
          menu={{ items: this.options.menu }}
          align={{ offset: [pos.x, pos.y] }}
        >
          <span />
        </Dropdown>,
        this.container,
      )
      document.addEventListener('mousedown', this.onMouseDown)
    }
  }

  onMouseDown = () => {
    this.timer = window.setTimeout(() => {
      this.toggleContextMenu(false)
    }, 200)
  }

  onContextMenu({ e }) {
    if (this.timer) {
      clearTimeout(this.timer)
      this.timer = 0
    }
    this.toggleContextMenu(true, { x: e.clientX, y: e.clientY })
  }

  delegateEvents() {
    this.cellView.on('cell:contextmenu', this.onContextMenu, this)
    return super.delegateEvents()
  }

  onRemove() {
    this.cellView.off('cell:contextmenu', this.onContextMenu, this)
  }
}

ContextMenuTool.config({
  tagName: 'div',
  isSVGElement: true,
})


const Appssssssssss = () => {


  // 注册 React 节点
  const [isExpanded, setIsExpanded] = useState(true);
  const [graphUse, setGraphUse] = useState();



  register({
    shape: "react-node",
    width: 200,
    height: 140,
    component: (props) => {
      // 当前自己的节点
      const { node } = props;

      const toggleExpand = () => {
        setIsExpanded(!isExpanded);
        console.log("自己当前节点", node);
        // 更新节点高度
        node.resize(200, isExpanded ? 40 : 200);
      };

      return (
        <div className="meta-node-wrappar">
          <div
            style={{
              backgroundColor: "#f0f0f0",
              padding: 10,
            }}
          >
            <span>标题</span>
            <span onClick={toggleExpand}>-----展开</span>
          </div>
          {isExpanded && (
            <div className="meta-node-wrappar-box">
              <div className="meta-node-wrappar-box-item">测试内容</div>
              <div className="meta-node-wrappar-box-item">测试内容</div>
              <div className="meta-node-wrappar-box-item">测试内容</div>
              <div className="meta-node-wrappar-box-item">测试内容</div>
            </div>
          )}
        </div>
      );
    },
  });

  const container = useRef();

  useEffect(() => {
    if (!container.current) return;

    const graph = new Graph({
      container: container.current,
      width: 800,
      height: 600,
      background: { color: '#F2F7FA' },
      grid: {
        visible: true,
        type: 'mesh',
        size: 20,
        color: '#aaaaaa',
        thickness: 1,
        colorSecond: '#888888',
        thicknessSecond: 3,
        factor: 4,
      },
      panning: {//平移配置
        enabled: true,
        modifiers: [],
        eventTypes: ['leftMouseDown'],
      },
      mousewheel: { //缩放配置
        enabled: true,
        modifiers: ['ctrl', 'meta'],
      },
      connecting: {
        allowBlank: false,
        allowLoop: false,
        snap: true,
        createEdge() {
          // 线样式
          return new Shape.Edge({
            label: "某某某关系",
            tools: [
              {
                name: 'contextmenu',
                args: {
                  menu: [
                    {
                      key: 'copy',
                      label: '复制',
                    },
                    {
                      key: 'paste',
                      label: '粘贴',
                    },
                    {
                      key: 'delete',
                      label: '删除',
                      type: 'danger',
                    },
                  ],
                },
              },
            ],
            attrs: {
              line: {
                sourceMarker: '',
                targetMarker: 'block',
                "stroke": "#6D85FF",
                "strokeWidth": 2
              },
            },
          })
        },
        allowBlank() {
          return false
        },
        allowLoop: true,
        allowNode: true,
        allowEdge: true,
        highlight: true,
        validateConnection({ sourceView, targetView, sourceMagnet, targetMagnet }) {
          if (targetMagnet) {
            return true;
          }
        },
      },
    });

    const ports = {
      groups: {
        list: {
          position: {
            name: "metaNodeWrapparBox",
            args: {
              start: 45,
            },
          },
          attrs: {
            circle: {
              r: 4,
              magnet: true,
              stroke: "#31d0c6",
              strokeWidth: 2,
              fill: "#fff",
            },
          },
        },
      },
      items: [
        { id: "port1", group: "list" },
        { id: "port2", group: "list" },
        { id: "port3", group: "list" },
        { id: "port4", group: "list" },
      ],
    };

    // const node = graph.addNode({
    //   shape: "react-node",
    //   x: 100,
    //   y: 100,
    //   id: 1,
    //   ports,
    // });

    // graph.addNode({
    //   shape: "react-node",
    //   x: 200,
    //   y: 200,
    //   id: 2,
    //   data: { name: "sunliusen " },
    //   ports,
    // });


    const menu = [
      {
        key: 'copy',
        label: '复制',
      },
      {
        key: 'paste',
        label: '粘贴',
      },
      {
        key: 'delete',
        label: '删除',
        type: 'danger',
      },
    ]



    Graph.registerEdgeTool('contextmenu', ContextMenuTool, true)
    Graph.registerNodeTool('contextmenu', ContextMenuTool, true)

    const source = graph.addNode({
      x: 180,
      y: 60,
      width: 100,
      height: 40,
      attrs: {
        body: {
          stroke: '#5F95FF',
          fill: '#EFF4FF',
          strokeWidth: 1,
        },
      },
      tools: [
        {
          name: 'contextmenu',
          args: {
            menu,
          },
        },
      ],
    })

    const target = graph.addNode({
      x: 320,
      y: 250,
      width: 100,
      height: 40,
      attrs: {
        body: {
          stroke: '#5F95FF',
          fill: '#EFF4FF',
          strokeWidth: 1,
        },
      },
      tools: [
        {
          name: 'contextmenu',
          args: {
            menu,
          },
        },
      ],
    })

    graph.addEdge({
      source,
      target,
      attrs: {
        line: {
          stroke: '#A2B1C3',
          strokeWidth: 2,
        },
      },
      tools: [
        {
          name: 'contextmenu',
          args: {
            menu,
          },
        },
      ],
    })
  }, [container]);

  return (
    <div>
      <div
        ref={container}
        style={{
          height: "500px",
        }}
      ></div>
    </div>
  );
};

export default Appssssssssss;
